package com.dks.repository.impl.pay;

import com.dks.mapper.PaymentOrderMapper;
import com.dks.mapper.UserCashCouponMapper;
import com.dks.mapper.UserClassHourPackageMapper;
import com.dks.models.PaymentOrder;
import com.dks.models.UserCashCoupon;
import com.dks.models.student.UserClassHourPackage;
import com.dks.repository.IWxPayRepository;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Date;

@Slf4j
@Repository
public class WxPayRepository implements IWxPayRepository {

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private UserClassHourPackageMapper userClassHourPackageMapper;
    @Autowired
    private UserCashCouponMapper userCashCouponMapper;


    @Override
    public String handleBuyPackagePayNotify(String xmlData) {

        final WxPayOrderNotifyResult notifyResult;
        try {
            notifyResult = this.wxPayService.parseOrderNotifyResult(xmlData);
        } catch (WxPayException e) {
            e.printStackTrace();
            return "fail";
        }
        log.error("微信返回数据=======>>>>" + notifyResult.toString());
        Long packageId = Long.parseLong(notifyResult.getOutTradeNo().split("-")[0]);
        UserClassHourPackage userClassHourPackage = userClassHourPackageMapper.selectById(packageId);
        if (userClassHourPackage == null) {
            return "fail";
        }

        if (userClassHourPackage.getPayStatus() == 0) {
            userClassHourPackageMapper.updatePayStatus(userClassHourPackage.getId(), 1, new Date());
            if (userClassHourPackage.getCashCouponId() != null) {
                UserCashCoupon userCashCoupon = userCashCouponMapper.select(userClassHourPackage.getCashCouponId());
                if (userCashCoupon != null) {
                    userCashCoupon.setIsUsedStatus(1);
                    userCashCoupon.setGmtModifyTime(new Date());
                    userCashCouponMapper.update(userCashCoupon);
                }
            }
            return WxPayNotifyResponse.success("成功");
        }
        return WxPayNotifyResponse.success("成功");
    }
}
